import {
  applicationadd,
  gsdlist,
  applicationitems,
  applicationblack,
  showArea
} from "../../../server/api";
import { env } from "../../../utils/env";
import {debounce} from '../../../server/shake'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    sheetshow: false,
    fileList: [],
    fileList2: [],
    imgnum1: "0",
    imgnum2: "0",
    list: [],
    result: [], //默认选中
    actions: [
      {
        id: 0,
        name: "营业执照",
      },
      {
        id: 1,
        name: "社区证明",
      },
    ],
    pupshow: false,
    columns: [],
    dpname: "", //店铺名称
    personame: "", //负责人
    phone: "", //联系电话
    businessname: "", //经营项
    address: "", //店铺地址
    detailadd: "", //详细地址
    zjtype: " ", //证件类型
    addressfilepath: "", //店铺图片地址
    oppositefilepath: "", //证件类型图片地址
    dpadd: "", //店铺地址
    zjname: "",
    type: "", //判断是否回显
    newdata: [],
    xDimension:'',
    yLongitude:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ type: options.type });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    if (this.data.type == 1) {
      // this.getdatadetail(); //回显
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // if(wx.getStorageSync('address') != '')
    // {
      this.getdata();
      this.getbusiness();
    // }
  },
  //经营项接口
  async getbusiness() {
    const res = await applicationitems();
    if (res.code == 200) {
      this.setData({ list: res.result });
    }
  },
  //归属地列表接口
  async getdata() {
    const value = await showArea();
    if (value.code == 200) {
      const source = value.result;
      //归属地列表接口
      const res = await gsdlist();
      if (res.code == 200) {
        const newsdata = res.result;
        var aname;
        var bname;
        var cname;
        var index1;
        var index2;
        var index3;
        for (let i = 0; i < newsdata.length; i++) {
          if (newsdata[i].id == source[0]) {
            aname = newsdata[i].pointsPlaceName;
            index1 = i;
            for (let j = 0; j < newsdata[i].children.length; j++) {
              if (newsdata[i].children[j].id == source[1]) {
                index2 = j;
                bname = newsdata[i].children[j].pointsPlaceName;
                if(newsdata[i].children[j].children == null)
                {
                  index3 = '';
                  cname = undefined;
                }else{
                  for (
                    let k = 0;
                    k < newsdata[i].children[j].children.length;
                    k++
                  ) {
                    if (newsdata[i].children[j].children[k].id == source[2]) {
                      index3 = k;
                      cname = newsdata[i].children[j].children[k].pointsPlaceName;
                    }
                  }
                }
               
              }
            }
          }
        }
        const name  = aname + (bname == undefined ? '' : '-' + bname ) + (cname == undefined  ? '' : '-' + cname)
          const id = source[2] == undefined ?  source[1] : source[1] == undefined ? source[0] : source[2]
          console.log( id,'value');
        this.setData({ dpadd: name.length > 15 ? name.slice(0,15) + '....'  : name,address:id });
      }
    }
  },
  //选取店铺地址
  onChanges(event) {
    const { picker, value, index } = event.detail;
    if (index == 0) {
      picker.setColumnValues(1, value[0].children == null ? [] : value[0].children);
      picker.setColumnValues(2,value[0].children == null ? [] : value[0].children[0].children == null ? [] : value[0].children[0].children);
    } else if (index === 1) {
      picker.setColumnValues(2, value[1].children == null ? [] : value[1].children);
    }
  },
  //详细地址
  detailadd(){
    const that = this
    wx.chooseLocation({
      success:function(res) {
        that.setData({detailadd:res.name, xDimension:res.latitude,yLongitude:res.longitude})
        // console.log(res.name); // 选择的位置名称
        // console.log(res.address); // 选择的位置地址
        console.log(res.latitude); // 选择的位置纬度
        console.log(res.longitude); // 选择的位置经度
      }
    })
  },
  //地址取消
  onCancel() {
    this.setData({ pupshow: false });
  },
  //店铺地址确认
  onConfirm(event) {
    const res = event.detail.value;
    const useraddress =
    (res[2] == undefined && res[1] == undefined) ?
    res[0].pointsPlaceName  :
     res[0].pointsPlaceName +
     ( 
     res[1] == undefined ? "-" + res[0].pointsPlaceName : "-" + res[1].pointsPlaceName )
    +
     (res[2] == undefined
       ? ""
       : "-" + res[2].pointsPlaceName);
      
       const ids =  (res[2] == undefined && res[1] == undefined) ? res[0].id : res[2] == undefined ? res[1].id : res[2].id == 12 ? '' : res[2].id
    this.setData({
      pupshow: false,
      address: ids,
      dpadd: res[0].id == "10" ? "" : useraddress,
    });
  },
  //选择店铺地址
  dtadd() {
    // this.setData({ pupshow: true });
  },
  //校验手机号
  isValidPhoneNumber(phoneNumber){
       const tel =  /^([0-9]{3,4}-)?[0-9]{7,8}$/
       const mobil =  /^1[3-9]\d{9}$/
       return  mobil.test(phoneNumber) || tel.test(phoneNumber)
  },
  submit: debounce(async function () {
    if (this.data.dpname == "") {
      wx.showToast({
        title: "店铺名称不能为空",
        icon: "none",
      });
    } else if (this.data.personame == "") {
      wx.showToast({
        title: "负责人不能为空",
        icon: "none",
      });
    } else if (this.data.phone == "") {
      wx.showToast({
        title: "电话不能为空",
        icon: "none",
      });
    }else if( this.isValidPhoneNumber(this.data.phone) == false){
      wx.showToast({
        title: "电话格式不正确",
        icon: "none",
      });
    } else if (this.data.businessname == "") {
      wx.showToast({
        title: "经营项不能为空",
        icon: "none",
      });
    } else if (this.data.address == "") {
      wx.showToast({
        title: "店铺地址不能为空",
        icon: "none",
      });
    } else if (this.data.detailadd == "") {
      wx.showToast({
        title: "详细地址不能为空",
        icon: "none",
      });
    } else if (this.data.zjtype === "") {
      wx.showToast({
        title: "证件类型不能为空",
        icon: "none",
      });
    } else if (this.data.fileList.length == 0) {
      wx.showToast({
        title: "请上传证件图片",
        icon: "none",
      });
    } else if (this.data.fileList2.length == 0) {
      wx.showToast({
        title: "请上传店铺照片",
        icon: "none",
      });
    } else {
      const opath = []; //证件类型
      const addpath = []; //店铺照片
      this.data.fileList.map((item) => {
        opath.push(item.paths);
      });
      this.data.fileList2.map((item) => {
        addpath.push(item.paths);
      });
      const params = {
        shopName: this.data.dpname,
        leader: this.data.personame,
        phone: this.data.phone,
        businessDirection: this.data.businessname,
        shopAdress: this.data.address,
        detailedAdress: this.data.detailadd,
        documentsType: this.data.zjtype,
        oppositefilepath: opath.join(","),
        addressfilepath: addpath.join(","),
        businessId: wx.getStorageSync("id"),
        xdimension:String(this.data.xDimension),
        ylongitude:String(this.data.yLongitude)
      };
      const res = await applicationadd(params);
      if (res.code == 200) {
        wx.showToast({
          title: "提交成功",
          icon: "success",
        });
        setTimeout(() => {
          wx.redirectTo({
            url: "/subPackagesA/pages/audit/audit",
          });
        }, 1000);
      } else {
        wx.showToast({
          title: "title",
          icon: "error",
        });
      }
    }
},3000),
  //选取经营项
  onChangelist(event) {
    console.log(event);
    this.setData({
      result: event.detail,
    });
  },
  onClose() {
    this.setData({ show: false });
  },
  //经营
  business() {
    this.setData({ show: true });
  },
  zjtap() {
    this.setData({ sheetshow: true });
  },
  sheetonClose() {
    this.setData({ sheetshow: false });
  },
  //证件类型选项
  onSelect(event) {
    this.setData({ zjtype: event.detail.id, zjname: event.detail.name });
  },
  onChange(event) {
    console.log(event,'eee');
    this.setData({
      result: event.detail,
    });
  },

  toggle(event) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },

  noop() {},
  //经营项目确定
  oksubmit() {
    const jy = this.data.result.join(",");
    this.setData({ businessname: jy });
    this.setData({ show: false });
  },
  //经营项取消
  nocancel() {
    this.setData({ show: false, result: [],businessname:'' });
  },
  //图片上传
  afterRead(event) {
    const { file } = event.detail; //获取所需要上传的文件列表
    let that = this;
    file.forEach((file) => {
      wx.uploadFile({
        filePath: file.tempFilePath,
        name: "file",
        url: `${env.baseURL}/sys/common/upload`,
        header: {
          "X-Access-Token": wx.getStorageSync("token") || "",
          "content-type": "multipart/form-data",
          accept: "application/json",
        },
        success: async function (e) {
          const imgInfo = JSON.parse(e.data);
          const arr = [];
          arr.push({
            ...file,
            url: imgInfo.message.save,
            paths: imgInfo.message.savePath,
          });
          that.setData({ fileList: [...that.data.fileList, ...arr] });
          that.setData({ imgnum1: that.data.fileList.length });
        },
      });
    });
  },
  afterRead2(event) {
    const { file } = event.detail; //获取所需要上传的文件列表
    let that = this;
    file.forEach((file) => {
      wx.uploadFile({
        filePath: file.tempFilePath,
        name: "file",
        url: `${env.baseURL}/sys/common/upload`,
        header: {
          "X-Access-Token": wx.getStorageSync("token") || "",
          "content-type": "multipart/form-data",
          accept: "application/json",
        },
        success: async function (e) {
          const imgInfo = JSON.parse(e.data);
          const arr = [];
          arr.push({
            ...file,
            url: imgInfo.message.save,
            paths: imgInfo.message.savePath,
          });
          that.setData({ fileList2: [...that.data.fileList2, ...arr] });
          that.setData({ imgnum2: that.data.fileList2.length });
        },
      });
    });
    wx.hideLoading();
  },
  //删除图片
  deleteImg(data) {
    const idx = data.detail.index;
    this.data.fileList.splice(idx, 1);
    this.setData({
      fileList: this.data.fileList,
      imgnum1: this.data.fileList.length,
    });
  },
  //删除图片
  deleteImg2(data) {
    const idx = data.detail.index;
    this.data.fileList2.splice(idx, 1);
    this.setData({
      fileList2: this.data.fileList2,
      imgnum2: this.data.fileList2.length,
    });
  },
  async getdatadetail() {
    const userid = wx.getStorageSync("id");
    const res = await applicationblack(userid);
    if (res.code == 200) {
      const arr1 = [];
      const arr2 = [];
      const obj = res.result;
      const source = obj.shopAdress.split(",");
      obj.pictures.map((item) => {
        if (item.picturetype == 5) {
          arr1.push({
            url: env.baseURL + "/" + item.picturePath,
            paths: item.picturePath,
          });
        } else {
          arr2.push({
            url: env.baseURL + "/" + item.picturePath,
            paths: item.picturePath,
          });
        }
      });
      this.setData({
        zjtype:obj.documentsType,
        fileList: arr1,
        imgnum1: arr1.length,
        imgnum2: arr2.length,
        fileList2: arr2,
        dpname: obj.shopName,
        personame: obj.leader,
        phone: obj.phone,
        businessname: obj.businessDirection,
        result: obj.businessDirection.split(","),
        detailadd: obj.detailedAdress,
        zjname: obj.documentsType == 0 ? "营业执照" : "社区证明",
      });
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
